package com.syqc.monitor.ui.list

import android.view.KeyEvent
import android.view.View
import androidx.activity.viewModels
import androidx.core.view.GravityCompat
import androidx.core.view.isVisible
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import autodispose2.autoDispose
import com.google.android.material.tabs.TabLayout
import com.gyf.immersionbar.ktx.immersionBar
import com.syqc.choose.team.ChooseTeamActivity
import com.syqc.choose.teamcar.TeamsActivity
import com.syqc.comlib.UserConstant
import com.syqc.comlib.base.BaseActivity
import com.syqc.comlib.rx.filterFast
import com.syqc.comlib.utils.ActivityResultUtil.launchAct
import com.syqc.comlib.utils.ActivityResultUtil.registerResultOk
import com.syqc.comlib.utils.sub
import com.syqc.comlib.utils.toast
import com.syqc.monitor.R
import com.syqc.monitor.databinding.ActivityMonitorListBinding
import com.syqc.monitor.databinding.IncludeListMonitorToolbarBinding
import com.syqc.monitor.databinding.IncludeMonitorEndBinding
import com.syqc.monitor.databinding.IncludeTabLayoutBinding
import com.syqc.monitor.databinding.IncludeViewpagerMatchBinding
import com.syqc.utils.Keys
import com.syqc.utils.NetDataUtil

/**
 *@Author Jasper
 *@Time   2020/11/11
 *@Desc   列表监控
 */
class ListMonitorActivity :
    BaseActivity<ActivityMonitorListBinding>(ActivityMonitorListBinding::inflate) {
    private val fragments = ArrayList<Fragment>()
    private val allCarsFragment by lazy { ListMonitorFragment() }
    private val offlineFragment by lazy { ListMonitorFragment() }
    private val runCarsFragment by lazy { ListMonitorFragment() }
    private val stopCarsFragment by lazy { ListMonitorFragment() }
    private val alarmCarsFragment by lazy { ListMonitorFragment() }
    private val arrearsCarsFragment by lazy { ListMonitorFragment() }
    private val locationCarsFragment by lazy { ListMonitorFragment() }
    private val accCarsFragment by lazy { ListMonitorFragment() }
    private val tabTitles = ArrayList<String>()
    private var mPagerAdapter: MViewPagerAdapter? = null

    private lateinit var mTabLayoutVB: IncludeTabLayoutBinding
    private lateinit var mListMonitorVB: IncludeMonitorEndBinding
    private lateinit var mViewPagerVB: IncludeViewpagerMatchBinding
    private lateinit var mMonitorBarVB: IncludeListMonitorToolbarBinding

    private val mViewModel: ListMonitorViewModel by viewModels()

    override fun initView() {
        mTabLayoutVB = IncludeTabLayoutBinding.bind(binding.root)
        mListMonitorVB = IncludeMonitorEndBinding.bind(binding.root)
        mViewPagerVB = IncludeViewpagerMatchBinding.bind(binding.root)
        mMonitorBarVB = IncludeListMonitorToolbarBinding.bind(binding.root)
        immersionBar { titleBar(mMonitorBarVB.listToolbar) }

        val stringArray: Array<String> = resources.getStringArray(R.array.tab_list_monitor)
        tabTitles.addAll(stringArray)
        mTabLayoutVB.tabLayout.tabMode = TabLayout.MODE_SCROLLABLE
        initViewPager()
        initViewModel()
        initEndView()
        setListener()
    }


    private fun initViewPager() {
        fragments.add(allCarsFragment)
        fragments.add(offlineFragment)
        fragments.add(runCarsFragment)
        fragments.add(accCarsFragment)
        fragments.add(stopCarsFragment)
        fragments.add(alarmCarsFragment)
        fragments.add(arrearsCarsFragment)
        fragments.add(locationCarsFragment)
        mPagerAdapter = MViewPagerAdapter(fragments, supportFragmentManager)
        mPagerAdapter!!.setPageTitle(tabTitles)
        mViewPagerVB.mViewPager.adapter = mPagerAdapter
        mViewPagerVB.mViewPager.offscreenPageLimit = 8
        mTabLayoutVB.tabLayout.setupWithViewPager(mViewPagerVB.mViewPager)

    }

    private fun initViewModel() {
        if (UserConstant.current_car_num > 300) {

            if (NetDataUtil.isSyncTree) {
                launcher.launchAct<TeamsActivity>(this) {
                    putExtra("isMap", true)
                }
            } else {
                launcher.launchAct<ChooseTeamActivity>(this) {
                    putExtra("isMap", true)
                }
            }

            mListMonitorVB.tvListAllCars.isVisible = false
        } else {
            mViewModel.getCarsLocation()
        }
        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(::toastObserver)

        mViewModel.gpsObserver.observe(this) {
            if (isRefresh) toast(R.string.toast_refresh_success)
            isRefresh = false
            val titles = ArrayList<String>()
            for ((index, entity) in it.withIndex()) {
                titles.add("${tabTitles[index]}(${entity.size})")
            }
            runOnUiThread {
                mPagerAdapter!!.setPageTitle(titles)
                mPagerAdapter!!.notifyDataSetChanged()
                allCarsFragment.setData(it[0])
                offlineFragment.setData(it[1])
                runCarsFragment.setData(it[2])
                accCarsFragment.setData(it[3])
                stopCarsFragment.setData(it[4])
                alarmCarsFragment.setData(it[5])
                arrearsCarsFragment.setData(it[6])
                locationCarsFragment.setData(it[7])
            }
        }
    }

    private var isRefresh = false
    override fun setListener() {
        mMonitorBarVB.ivToolbarStart.setOnClickListener {
            if (isHome) {
                startHomeActivity()
            }
            finish()
        }

        mMonitorBarVB.ivToolbarCenter.filterFast {
            isRefresh = true
            mViewModel.getCarsLocation()
        }

        mMonitorBarVB.ivToolbarEnd.setOnClickListener {
            if (binding.listDrawerLayout.isDrawerOpen(GravityCompat.END)) {
                binding.listDrawerLayout.closeDrawer(GravityCompat.END)
            } else {
                binding.listDrawerLayout.openDrawer(GravityCompat.END)
            }
        }

        mListMonitorVB.tvListChooseCar.filterFast {
            mMonitorBarVB.tvToolbarTitle.setText(R.string.title_monitor_list)
            binding.listDrawerLayout.closeDrawer(GravityCompat.END)

            if (NetDataUtil.isSyncTree) {
                launcher.launchAct<TeamsActivity>(this) {
                    putExtra("isMap", true)
                }
            } else {
                launcher.launchAct<ChooseTeamActivity>(this) {
                    putExtra("isMap", true)
                }
            }
        }
        mListMonitorVB.tvListClear.filterFast {
            mMonitorBarVB.tvToolbarTitle.setText(R.string.title_monitor_list)
            mViewModel.isClear = true
            clearData()
        }
        mListMonitorVB.tvListAllCars.filterFast {
            binding.listDrawerLayout.closeDrawer(GravityCompat.END)
            mMonitorBarVB.tvToolbarTitle.setText(R.string.desc_map_all_car)
            mViewModel.isClear = false
            mViewModel.teamId = ""
            mViewModel.getCarsLocation()
        }
        mListMonitorVB.rdbListPlate.filterFast {
            mListMonitorVB.rdbListPlate.isChecked = true
            setPlateName(true)
            mViewModel.sortByType = "carPlate"
        }
        mListMonitorVB.rdbListCarName.filterFast {
            mListMonitorVB.rdbListCarName.isChecked = true
            setPlateName(false)
            mViewModel.sortByType = "carName"
        }
        mListMonitorVB.cbListTime.filterFast {
            mListMonitorVB.cbListTime.isSelected = !ListMonitorModel.instance.getTimeShow()
            ListMonitorModel.instance.setTime(mListMonitorVB.cbListTime.isSelected)
            notifyFragment()
        }
        mListMonitorVB.cbListState.filterFast {
            mListMonitorVB.cbListState.isSelected = !ListMonitorModel.instance.getStateShow()
            ListMonitorModel.instance.setState(mListMonitorVB.cbListState.isSelected)
            notifyFragment()
        }
        mListMonitorVB.cbListSpeed.filterFast {
            mListMonitorVB.cbListSpeed.isSelected = !ListMonitorModel.instance.getSpeedShow()
            ListMonitorModel.instance.setSpeed(mListMonitorVB.cbListSpeed.isSelected)
            notifyFragment()
        }
        mListMonitorVB.cbListDriver.filterFast {
            mListMonitorVB.cbListDriver.isSelected = !ListMonitorModel.instance.getDriverShow()
            ListMonitorModel.instance.setDriver(mListMonitorVB.cbListDriver.isSelected)
            notifyFragment()
        }
        mListMonitorVB.cbListMile.filterFast {
            mListMonitorVB.cbListMile.isSelected = !ListMonitorModel.instance.getMileShow()
            ListMonitorModel.instance.setMile(mListMonitorVB.cbListMile.isSelected)
            notifyFragment()
        }
        mListMonitorVB.cbListRunStop.filterFast {
            mListMonitorVB.cbListRunStop.isSelected = !ListMonitorModel.instance.getRunStopShow()
            ListMonitorModel.instance.setRunStop(mListMonitorVB.cbListRunStop.isSelected)
            notifyFragment()
        }
        //////////
        mListMonitorVB.cbOil.filterFast {
            mListMonitorVB.cbOil.isSelected = !ListMonitorModel.instance.getOilShow()
            ListMonitorModel.instance.setOilShow(mListMonitorVB.cbOil.isSelected)
            notifyFragment()
        }

        mListMonitorVB.cbWater.filterFast {
            mListMonitorVB.cbWater.isSelected = !ListMonitorModel.instance.getWaterShow()
            ListMonitorModel.instance.setWaterShow(mListMonitorVB.cbWater.isSelected)
            notifyFragment()
        }

        mListMonitorVB.cbTemp.filterFast {
            mListMonitorVB.cbTemp.isSelected = !ListMonitorModel.instance.getTempShow()
            ListMonitorModel.instance.setTempShow(mListMonitorVB.cbTemp.isSelected)
            notifyFragment()
        }

        mListMonitorVB.cbDamp.filterFast {
            mListMonitorVB.cbDamp.isSelected = !ListMonitorModel.instance.getDempShow()
            ListMonitorModel.instance.setDempShow(mListMonitorVB.cbDamp.isSelected)
            notifyFragment()
        }

        mListMonitorVB.cbLoad.filterFast {
            mListMonitorVB.cbLoad.isSelected = !ListMonitorModel.instance.getLoadShow()
            ListMonitorModel.instance.setLoadShow(mListMonitorVB.cbLoad.isSelected)
            notifyFragment()
        }

        binding.listDrawerLayout.addDrawerListener(object : DrawerLayout.SimpleDrawerListener() {
            override fun onDrawerClosed(drawerView: View) {
                super.onDrawerClosed(drawerView)
                mMonitorBarVB.ivToolbarEnd.isSelected = false
            }

            override fun onDrawerOpened(drawerView: View) {
                super.onDrawerOpened(drawerView)
                mMonitorBarVB.ivToolbarEnd.isSelected = true
            }
        })

    }

    private fun notifyFragment() {
        allCarsFragment.notifyDataSetChanged()
        offlineFragment.notifyDataSetChanged()
        runCarsFragment.notifyDataSetChanged()
        stopCarsFragment.notifyDataSetChanged()
        alarmCarsFragment.notifyDataSetChanged()
        arrearsCarsFragment.notifyDataSetChanged()
        locationCarsFragment.notifyDataSetChanged()
        accCarsFragment.notifyDataSetChanged()
    }

    //设置是否是车牌排序
    private fun setPlateName(isPlate: Boolean) {
        allCarsFragment.setPlatName(isPlate)
        offlineFragment.setPlatName(isPlate)
        runCarsFragment.setPlatName(isPlate)
        stopCarsFragment.setPlatName(isPlate)
        alarmCarsFragment.setPlatName(isPlate)
        arrearsCarsFragment.setPlatName(isPlate)
        locationCarsFragment.setPlatName(isPlate)
        accCarsFragment.setPlatName(isPlate)
    }

    private fun clearData() {
        mViewModel.teamId = ""
        mPagerAdapter!!.setPageTitle(tabTitles)
        mPagerAdapter!!.notifyDataSetChanged()
        allCarsFragment.clear()
        offlineFragment.clear()
        runCarsFragment.clear()
        stopCarsFragment.clear()
        alarmCarsFragment.clear()
        arrearsCarsFragment.clear()
        locationCarsFragment.clear()
        accCarsFragment.clear()
    }

    private fun initEndView() {
        val isPlate = mViewModel.sortByType == "carPlate"
        setPlateName(isPlate)
        mListMonitorVB.rdbListPlate.isChecked = isPlate
        mListMonitorVB.rdbListCarName.isChecked = mViewModel.sortByType == "carName"
        mListMonitorVB.cbListTime.isSelected = ListMonitorModel.instance.getTimeShow()
        mListMonitorVB.cbListState.isSelected = ListMonitorModel.instance.getStateShow()
        mListMonitorVB.cbListSpeed.isSelected = ListMonitorModel.instance.getSpeedShow()
        mListMonitorVB.cbListDriver.isSelected = ListMonitorModel.instance.getDriverShow()
        mListMonitorVB.cbListMile.isSelected = ListMonitorModel.instance.getMileShow()
        mListMonitorVB.cbListRunStop.isSelected = ListMonitorModel.instance.getRunStopShow()
        mListMonitorVB.cbOil.isSelected = ListMonitorModel.instance.getOilShow()
        mListMonitorVB.cbWater.isSelected = ListMonitorModel.instance.getWaterShow()
        mListMonitorVB.cbTemp.isSelected = ListMonitorModel.instance.getTempShow()
        mListMonitorVB.cbDamp.isSelected = ListMonitorModel.instance.getDempShow()
        mListMonitorVB.cbLoad.isSelected = ListMonitorModel.instance.getLoadShow()
    }

    private val launcher = registerResultOk { result ->
        result.data?.let {
            val teamId = it.getStringExtra(Keys.INTENT_TEAM_ID) ?: ""
            val teamName = it.getStringExtra(Keys.INTENT_TEAM_NAME) ?: ""
//                val carNum = it.getStringExtra(Keys.INTENT_TEAM_NUM)?:"0"
            mViewModel.isClear = false
            mViewModel.teamId = teamId
            mViewModel.getCarsLocation()
            mMonitorBarVB.tvToolbarTitle.text = "${sub(teamName, 10)}"
            mViewPagerVB.mViewPager.currentItem = 0
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (binding.listDrawerLayout.isDrawerOpen(GravityCompat.END)) {
            binding.listDrawerLayout.closeDrawer(GravityCompat.END)
            return false
        }
        return super.onKeyDown(keyCode, event)
    }
}


class MViewPagerAdapter(private val fragments: ArrayList<Fragment>, manager: FragmentManager) :
    FragmentStatePagerAdapter(manager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
    private var tabTitles = ArrayList<String>()
    override fun getCount(): Int {
        return fragments.size
    }


    override fun getPageTitle(position: Int): CharSequence {
        return tabTitles[position]
    }

    override fun getItem(position: Int): Fragment {
        return fragments[position]
    }

    fun setPageTitle(tabTitles: ArrayList<String>) {
        this.tabTitles = tabTitles

    }
}